<template>
  <view class="root">
    <scroll-view scroll-y class="scroll-view">
      <view class="content">
        <view class="card padding">
          <view class="flexr align-center">
            <image class="icon" src="../../static/addr.png"></image>
            <text class="card-name">{{ store.headofficeName }}</text>
          </view>
          <view class="shop-addr"> 地址: {{ store.address }} </view>
        </view>

        <view class="card">
          <view class="card-title">
            <view class="card-name">到店时间</view>
          </view>
          <view class="card-content">
            <view class="item-title"
              >选择日期和时间<text class="required">*</text></view
            >
            <view class="field flexr align-center" @click="showDatePicker">
              <view class="field-text">{{
                appointmentDates[appointmentDateIndex]?.dateDay
              }}</view>
              <image class="field-icon" src="@/static/ic_date.png"></image>
            </view>
            <view class="times">
              <view
                class="flexr"
                v-for="(tg, gindex) in appointmentDates[appointmentDateIndex]
                  ?.times"
                :key="gindex"
              >
                <!-- <view class="time active">09:00-10:00</view> -->
                <view
                  class="time"
                  :class="{
                    active: appointmentTime === t.Item,
                    disable: t.IsCan != '1',
                  }"
                  v-for="(t, tindex) in tg"
                  :key="tindex"
                  @click="appointmentTime = t.Item"
                  >{{ t.Item }}</view
                >
                <!-- <view class="time">14:00-16:00</view> -->
                <view
                  class="time hide"
                  v-for="tt in 3 - tg.length"
                  :key="tt"
                ></view>
              </view>
              <!-- <view class="flexr">
                <view class="time">20:00-21:00</view>
                <view class="time">21:00-22:00</view>
                <view class="time hide"></view>
              </view> -->
            </view>
          </view>
        </view>

        <view class="card">
          <view class="card-title">
            <view class="card-name">项目</view>
          </view>
          <view class="card-content">
            <view class="item-title"
              >预约项目<text class="required">*</text></view
            >
            <view class="field flexr align-center">
              <!-- <view class="field-text">验光</view> -->
              <picker
                class="field-text"
                :value="appointmentItemIndex"
                :range="appointmentItemsKeys"
                @change="onAppointmentItemChange"
              >
                <view>{{
                  appointmentItems[appointmentItemIndex]?.dictionaryKey
                }}</view>
              </picker>
              <image
                class="field-icon proj-icon"
                src="@/static/arrow_down.png"
                mode="widthFix"
              ></image>
            </view>
            <view class="item-title">项目描述</view>
            <view class="proj-desc">
              {{ appointmentItems[appointmentItemIndex]?.remark }}
            </view>
          </view>
        </view>

        <view class="card">
          <view class="card-title">
            <view class="card-name">导购员</view>
          </view>
          <view class="card-content">
            <view class="item-title"
              >选择导购员<text class="required">*</text></view
            >
            <view class="field flexr align-center" @click="showSalerPicker">
              <view class="field-text">{{
                appointmentClerksNames[appointmentClerksIndex]
              }}</view>
              <image
                class="field-icon proj-icon"
                src="@/static/arrow_down.png"
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>

        <view class="primary-button" @click="submitAppointment">
          提交预约
        </view>
      </view>
    </scroll-view>

    <uni-popup
      ref="datePickerRef"
      @change="({ show }) => (datePickerShow = show)"
      type="bottom"
      background-color="#fff"
      border-radius="30rpx"
      :mask-click="false"
    >
      <myDatePicker
        :show="datePickerShow"
        :years="appointmentAvaliableYears"
        :months="appointmentAvaliableMonths"
        :days="appointmentAvaliableDays"
        @onCancel="onCancelDatePicker"
        @onConfirm="onConfirmDatePicker"
      ></myDatePicker>
    </uni-popup>
    <uni-popup
      ref="salerPickerRef"
      type="bottom"
      background-color="#fff"
      border-radius="30rpx"
      :mask-click="false"
    >
      <salerPicker
        :index="appointmentClerksIndex"
        :items="appointmentClerks"
        @onCancel="onCancelSalerPicker"
        @onConfirm="onConfirmSalerPicker"
      ></salerPicker>
    </uni-popup>
  </view>
</template>

<script setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, computed, watch } from "vue";
import myDatePicker from "@/subpages/widgets/myDatePicker.vue";
import salerPicker from "@/subpages/widgets/salerPicker.vue";
import { useShopStore } from "@/store/shop";
import { useAppointmentStore } from "@/store/appointment";
import {
  GetDictionaryByType,
  GetAppointmentTime,
  GetRelationClerkList,
} from "@/api/api.js";
const shopStore = useShopStore();
const appointmentStore = useAppointmentStore();
const store = ref({});
const datePickerShow = ref(false);
const datePickerRef = ref(null);
const salerPickerRef = ref(null);
const appointmentItems = ref([]);
const appointmentItemIndex = ref(0);
const appointmentDates = ref([]);
const appointmentDateIndex = ref(0);
const appointmentTime = ref();
const appointmentAvaliableYears = ref([]);
const appointmentAvaliableMonths = ref([]);
const appointmentAvaliableDays = ref([]);
const appointmentClerks = ref([]);
const appointmentClerksIndex = ref(0);

const appointmentItemsKeys = computed(() =>
  appointmentItems.value.map((item) => item.dictionaryKey)
);
const appointmentClerksNames = computed(() =>
  appointmentClerks.value.map((item) => item.clerk_Name)
);

watch(
  () => appointmentDateIndex.value,
  () => {
    appointmentTime.value = "";
  }
);

onLoad(({ storesId }) => {
  store.value =
    shopStore.nearby.find((item) => item.storesId == storesId) || {};
  GetDictionaryByType(store.value.custAccountCode).then((data) => {
    // console.log("GetDictionaryByType", data);
    appointmentItems.value = data.map((item) => {
      let remark = "";
      try {
        remark = JSON.parse(item.dictJson).remark;
      } catch {}
      delete item.dictJson;
      return { ...item, remark };
    });
    appointmentItemIndex.value = 0;
  });
  GetAppointmentTime(store.value.custAccountCode).then((data) => {
    // console.log("GetAppointmentTime", data);
    const years = new Set();
    const months = new Set();
    const days = new Set();
    appointmentDates.value = data.map((item) => {
      const [y, m, d] = item.dateDay.split("-");
      years.add(y);
      months.add(m);
      days.add(d);
      let times = [];
      try {
        times = JSON.parse(item.isCanAppointment);
      } catch {}
      delete item.isCanAppointment;
      const allTimes = [...times];
      // times 拆分为分组，每组3个
      times = times.reduce((acc, cur, index) => {
        const groupIndex = Math.floor(index / 3);
        if (!acc[groupIndex]) {
          acc[groupIndex] = [];
        }
        acc[groupIndex].push(cur);
        return acc;
      }, []);

      return { ...item, times, allTimes };
    });
    appointmentAvaliableYears.value = [...years];
    appointmentAvaliableMonths.value = [...months];
    appointmentAvaliableDays.value = [...days];
    appointmentDateIndex.value = 0;
  });
  GetRelationClerkList(store.value.custAccountCode).then((data) => {
    // console.log("GetRelationClerkList", data);
    appointmentClerks.value = data;
  });
});

function onAppointmentItemChange(e) {
  appointmentItemIndex.value = e.detail.value;
}

function showDatePicker() {
  datePickerRef.value?.open("bottom");
}
function onCancelDatePicker() {
  datePickerRef.value?.close();
}
function onConfirmDatePicker(date) {
  datePickerRef.value?.close();
  appointmentDateIndex.value = appointmentDates.value.findIndex(
    (item) => item.dateDay == date
  );
}
function showSalerPicker() {
  salerPickerRef.value?.open("bottom");
}
function onCancelSalerPicker() {
  salerPickerRef.value?.close();
}
function onConfirmSalerPicker(index) {
  salerPickerRef.value?.close();
  appointmentClerksIndex.value = index;
}
function submitAppointment() {
  if (!appointmentTime.value) {
    uni.showToast({
      title: "请选择到店时间",
      icon: "none",
    });
    return;
  }

  appointmentStore.addAppointment(
    appointmentTime.value,
    appointmentItemsKeys.value[appointmentItemIndex.value],
    appointmentDates.value[appointmentDateIndex.value]?.dateDay,
    1,
    appointmentDates.value[appointmentDateIndex.value].allTimes.findIndex(
      (time) => time.Item === appointmentTime.value
    ),
    '备注',
    appointmentClerks.value[appointmentClerksIndex.value].clerk_Id,
    store.value.custAccountCode,
  );
}
</script>

<style lang="scss">
.root {
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
  overflow-y: scroll;
}
.content {
  padding: 32rpx;
  .card {
    background-color: white;
    border-radius: 20rpx;
    // padding: 30rpx;
    &.padding {
      padding: 30rpx;
    }
    .icon {
      height: 48rpx;
      width: 48rpx;
      margin-right: 15rpx;
    }
    .card-name {
      color: $text-color1;
      font-size: 32rpx;
    }
    .shop-addr {
      margin-top: 20rpx;
      color: $text-color5;
    }
    .card-title {
      height: 90rpx;
      padding: 0 30rpx;
      border-bottom: 1px solid $divider-color;
      display: flex;
      align-items: center;
    }
    .card-content {
      padding: 32rpx;
      .item-title {
        color: $text-color2;
        margin-bottom: 15rpx;
      }
      .required {
        color: red;
        margin-left: 10rpx;
      }
    }
    .field {
      border: 1px solid #e5e5e5ff;
      border-radius: 13rpx;
      height: 80rpx;
      padding: 0 30rpx;
      .field-text {
        font-size: 32rpx;
        color: $text-color1;
        flex: 1;
      }
      .field-icon {
        width: 36rpx;
        height: 36rpx;
      }
      .proj-icon {
        width: 30rpx;
      }
    }
    .field + .item-title {
      margin-top: 15rpx;
    }
    .proj-desc {
      border: 1px solid #e5e5e5ff;
      border-radius: 13rpx;
      padding: 24rpx 30rpx;
      font-size: 32rpx;
      background-color: #f3f3f3ff;
    }
    .times {
      .time {
        flex: 1;
        border: 1px solid #e5e5e5ff;
        border-radius: 13rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        // line-height: 80rpx;
        text-align: center;
        height: 80rpx;
        margin-top: 15rpx;
        // overflow: hidden;
        color: $text-color1;
        font-size: 24rpx;
        padding: 0 10rpx;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        &.hide {
          border: none;
        }
        &.active {
          background-color: #34b5a019;
          color: $primary-color;
        }
        &.disable {
          color: #999999;
          pointer-events: none;
        }
      }
      .time + .time {
        margin-left: 15rpx;
      }
    }
  }
  .card + .card {
    margin-top: 32rpx;
  }
  .primary-button {
    margin-top: 48rpx;
    margin-bottom: 26rpx;
  }
}
</style>
